Django + JQuery + ajax实时显示数据
1 创建django项目 :NowtimeData and APP :Demo
>>django-admin startproject NowtimeData
>>python manage.py startapp Demo
2 配置settings.py
①插入Demo
②配置模板路径
----BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
----TEMPLATES = [
'DIRS': [os.path.join(BASE_DIR, 'templates').replace('\\', '/')], # 修改 模板目录 ]
----STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static_collected')
----补充
# LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = 'zh-hans' # 简体中文
# TIME_ZONE = 'UTC'
TIME_ZONE = 'Asia/Shanghai' # 时区
③在APP Demo里创建templates和static,templates里新建ajax_test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/api/ajax/" method="get">
a:<input type="text" name="a" id="a"><br>
b:<input type="text" name="b" id="b"><br>
<p>温度:<span id="temp"></span></p>
<p>湿度:<span id="hum"></span></p>
<button type="button" id="sum">Calc</button>
</form>
<script src="http://apps.bdimg.com/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
setInterval(function () {
$(document).ready(function () {
var a = $('#a').val();
var b = $('#b').val();
//add是urls.py里的路由
$.get("/api/ajax/", {'a':a, 'b':b}, function (ret) {
//console.log(typeof ret);
var data = JSON.parse(ret);
//console.log(data[0]["fields"]);
//console.log(typeof Number(data[0]["fields"]["temp"]));
temp = Number(data[0]["fields"]["temp"]).toFixed(1);
hum = Number(data[0]["fields"]["hum"]).toFixed(1);
$("#temp").html(temp);
$("#hum").html(hum);
})
});
},1000);
</script>
</body>
</html>
或者通过点击事件来触发
<script>
$(document).ready(function () {
$("#sum").click(function () {
var d = $('#d').val();
var e = $('#e').val();
//add是urls.py里的路由
$.get("/add/", {'d': d, 'e': e}, function (ret) {
{#console.log(typeof ret);#}
console.log(ret);
$("#result").html(ret);
})
})
});
</script>
④在view.py中编辑代码
def adder(request):
# a = request.GET['a']
# b = request.GET['b']
# a = random.randint(1, 10)
# b = random.randint(1, 10)
# c = int(a)+int(b)
return render(request, 'ajax_test.html')
⑤建立数据api接口 api.py
from rest_framework import serializers
from rest_framework.response import Response
from rest_framework.decorators import api_view
from website.models import Room, Recv_data, Send_data # 得到数据库
from django.http import HttpResponse, JsonResponse
class Room_Admin(serializers.ModelSerializer):
class Meta:
depth = 1
model = Room
fields = '__all__'
class Recv_Admin(serializers.ModelSerializer):
class Meta:
depth = 1
model = Recv_data
fields = '__all__'
class Send_Admin(serializers.ModelSerializer):
class Meta:
depth = 1
model = Send_data
fields = '__all__'
from django.core.serializers import serialize
@api_view(['GET', 'POST'])
def ajaxData(request): # 在url.py里添加路由
# 房间管理
room_data = Room.objects.all()
roomData= Room_Admin(room_data, many=True)
recv_data = Recv_data.objects.all()
recvData = Recv_Admin(recv_data, many=True)
send_data = Send_data.objects.all()
sendData = Send_Admin(send_data, many=True)
room2_info = Recv_data.objects.filter(floor=2)
room3_info = Recv_data.objects.filter(floor=3)
room4_info = Recv_data.objects.filter(floor=4)
room5_info = Recv_data.objects.filter(floor=5)
room6_info = Recv_data.objects.filter(floor=6)
room2_info = serialize('json', room2_info, fields=['room', 'temp', 'status', 'mode', 'level', 'hum', 'co2', 'pm25', 'tvoc'])
room3_info = serialize('json', room3_info, fields=['room', 'temp', 'status', 'mode', 'level', 'hum', 'co2', 'pm25', 'tvoc'])
room4_info = serialize('json', room4_info, fields=['room', 'temp', 'status', 'mode', 'level', 'hum', 'co2', 'pm25', 'tvoc'])
room5_info = serialize('json', room5_info, fields=['room', 'temp', 'status', 'mode', 'level', 'hum', 'co2', 'pm25', 'tvoc'])
room6_info = serialize('json', room6_info, fields=['room', 'temp', 'status', 'mode', 'level', 'hum', 'co2', 'pm25', 'tvoc'])
# print(room2_info)
# return Response({'room_admin': roomData.data, 'recv_data': recvData.data, 'send_data': sendData.data})
# return HttpResponse(str({'room_admin': roomData.data, 'recv_data': recvData.data, 'send_data': sendData.data}))
return HttpResponse(room2_info)
⑥ 添加url.py
path('add/', views.adder),
path('api/ajax/', api.ajaxData),
⑦补充js for循环写数据
setInterval(function () {
$(document).ready(function () {
var a = $('#a').val();
var b = $('#b').val();
//add是urls.py里的路由
$.get("/api/ajax/", {'a':a, 'b':b}, function (ret) {
//console.log(typeof ret);
var data = JSON.parse(ret);
//console.log(data[0]["fields"]);
function room(room, a){
var temp = Number(data[a]["fields"]["temp"]).toFixed(1);
var status = data[a]["fields"]["status"];
if (status=='0'){
status="关";
$("#"+room).css({"background": "green"});
}
else if (status=='1'){
status='开';
$("#"+room).css({"background": "grey"});
}
else {
status='未知';
$("#"+room).css({"background": "purple"});
}
$("#temp_"+room).html(temp);
$("#status_"+room).html(status);
}
for (var i=8206;i<8230;i++){
room(i,i-8201)
}
})
});
},1000);